package core

import (
	"log"

	"gorm.io/gorm"
)

func CreateConference(db *gorm.DB, ConferId, RoomId, Elogo string) {
	conference := Conference{
		ConferId: ConferId,
		RoomId:   RoomId,
		Elogo:    Elogo,
	}
	result := db.Create(&conference)

	if result.Error != nil {
		log.Fatalf("Failed to create conference: %v", result.Error)
	} else {
		log.Printf("conference created with ID: %d", conference.Id)
		log.Printf("创建成功: %+v", conference)
	}
}

func GetConferenceByConferId(db *gorm.DB, ConferId string) (*Conference, error) {
	var conference *Conference
	result := db.First(&conference, "confer_id = ?", ConferId)
	if result.Error != nil {
		log.Printf("Conference not found: %v", result.Error)
		return nil, result.Error
	}
	return conference, nil
}

func GetAllConferences(db *gorm.DB) ([]*Conference, error) {
	var conferences []*Conference
	result := db.Find(&conferences)

	if result.Error != nil {
		log.Printf("Error retrieving conferences: %v", result.Error)
		return nil, result.Error
	}

	return conferences, nil
}

func GetConferenceByField(db *gorm.DB, conferid, elogo string) ([]*Conference, error) {
	var conferences []*Conference
	result := db.Where(&Conference{ConferId: conferid, Elogo: elogo}).Find(&conferences) //推荐写法，防止大小写敏感问题
	// result := db.Where("confer_id = ? AND elogo = ?", conferid, elogo).Find(&conferences)  //不推荐
	if result.Error != nil {
		log.Printf("Error retrieving conferences: %v", result.Error)
		return nil, result.Error
	}

	return conferences, nil
}

func UpdateConference(db *gorm.DB, ConferId, status string) {
	var conference Conference
	result := db.First(&conference, &Conference{ConferId: ConferId})
	// result := db.First(&conference, "confer_id = ?", ConferId)  //不推荐
	if result.Error != nil {
		log.Printf("Conference not found: %v", result.Error)
		return
	}

	conference.Status = status
	db.Save(&conference)
	log.Printf("Updated conference status: %+v", conference)
}

func DeleteConference(db *gorm.DB, id int64) {

	var conference Conference
	result := db.Delete(&conference, id)

	if result.Error != nil {
		log.Printf("Failed to delete conference: %v", result.Error)
		return
	}
	log.Printf("Conference deleted: %d", id)
}
